package org.jeecg.modules.online.desform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.online.desform.entity.DesignFormData;
import org.jeecg.modules.online.desform.service.IDesignFormDataService;
import org.jeecg.modules.online.desform.service.IDesignFormService;
import org.jeecg.modules.online.desform.util.DesformUtils;
import org.jeecg.modules.online.desform.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 表单设计器 外部链接
 * @Author: jeecg-boot
 * @Date: 2019-05-16
 * @Version: V1.0
 */
@RestController("designFormExtController")
@RequestMapping("/desform/ext")
public class DesignFormExtController {

    @Autowired
    private IDesignFormService designFormService;
    @Autowired
    private IDesignFormDataService designFormDataService;

    @Value("${jeecg.desform.theme-color}")
    private String desformThemeColor;

    @Value("${jeecg.desform.upload-type}")
    private String desformUploadType;

    /**
     * 外部表单新增页面地址
     */
    @GetMapping("/{desformCode}")
    public ModelAndView externalAddDesformData(@PathVariable("desformCode") String desformCode, @RequestParam(name = "reuseId", required = false) String reuseId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_ADD;
        if (StringUtils.isNotBlank(reuseId)) {
            urlType = CommonConstant.DESIGN_FORM_URL_TYPE_REUSE;
        } else {
            reuseId = "add";
        }
        return this.doFormView(modelAndView, urlType, desformCode, reuseId, null, request);
    }

    /**
     * 外部表单修改页面地址
     */
    @GetMapping("/{desformCode}/{dataId}")
    public ModelAndView externalEditDesformData(@PathVariable("desformCode") String desformCode, @PathVariable("dataId") String dataId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_EDIT;
        return this.doFormView(modelAndView, urlType, desformCode, dataId, null, request);
    }

    /**
     * 外部链接新增接口，不需要Token验证
     *
     * @param desformCode
     * @param designFormData
     * @return
     */
    @PostMapping("/{desformCode}")
    public Result extAdd(@PathVariable("desformCode") String desformCode, @RequestBody DesignFormData designFormData) {
        designFormData.setDesformCode(desformCode);
        return designFormDataService.addOne(designFormData);
    }

    /**
     * 外部链接修改接口，不需要Token验证
     */
    @PutMapping("/{desformCode}/{dataId}")
    public Result extEdit(@PathVariable("desformCode") String desformCode, @PathVariable("dataId") String dataId, @RequestBody DesignFormData designFormData) {
        designFormData.setDesformCode(desformCode);
        return designFormDataService.editOne(designFormData);
    }

    /**
     * 请求成功后返回的页面
     */
    @GetMapping("/success")
    public ModelAndView doSuccess(@RequestParam("desformCode") String desformCode, @RequestParam("dataId") String dataId, ModelAndView mv, HttpServletRequest request) {
        ModelAndView mv1 = new ModelAndView();
        mv1 = designFormService.queryFormViewByCode(desformCode, dataId, null, mv1);
        Map<String, Object> model = mv1.getModel();
        // 获取数据
        JSONObject designFormData = JSON.parseObject(JSON.parseObject(JSON.toJSONString(model.get("designFormData"))).getString("desformDataJson"));
        // 获取设计json
        JSONObject designForm = JSON.parseObject(JSON.toJSONString(model.get("designForm")));
        String desformDesignJson = designForm.getString("desformDesignJson");
        JSONObject json = JSON.parseObject(desformDesignJson);
        JSONArray dataList = json.getJSONArray("list");
        // 获取所有的字段
        List<JSONObject> widgets = new ArrayList<>();
        // 忽略部分显示
        List<String> ignores = Arrays.asList("button", "buttons", "grid", "card", "tabs", "text", "sub-table-design", "divider");
        DesformUtils.recursiveAllWidget(dataList, (type, item, parent) -> {
            if (type==null || !ignores.contains(type.getType())) {
                JSONObject widget = new JSONObject();
                String key = item.getString("model");
                String value = designFormData.getString(key);
                // 不展示空数据
                if (StringUtils.isNotBlank(value)) {
                    widget.put("title", item.getString("name"));
                    widget.put("modal", key);
                    widget.put("value", value);
                    widgets.add(widget);
                }
            }
        });
        mv.addObject("widgets", JSON.toJSONString(widgets));
        mv.setViewName("desform/result/success");
        return mv;
    }

    /**
     * 获取服务器地址
     *
     * @param request
     * @return
     */
    private String getBaseUrl(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        return scheme + "://" + serverName + ":" + serverPort + contextPath;
    }

    /**
     * @param mv
     * @param urlType
     * @param desformCode
     * @param dataId       数据Id，修改时用到
     * @param onlineDataId
     * @param request
     * @return
     */
    private ModelAndView doFormView(ModelAndView mv, String urlType, String desformCode, String dataId, String onlineDataId, HttpServletRequest request) {
        try {
            mv = designFormService.queryFormViewByCode(desformCode, dataId, onlineDataId, true, mv);
            // 公共属性
            mv.addObject("action", CommonConstant.DESIGN_FORM_URL_TYPE_REUSE.equals(urlType) ? CommonConstant.DESIGN_FORM_URL_TYPE_ADD : urlType);
            mv.addObject("themeColor", desformThemeColor);
            mv.addObject("uploadType", desformUploadType);
            mv.addObject("baseURL", this.getBaseUrl(request));
            mv.addObject("qiniuConfig", QiniuUtils.getConfig().toJSONString());
            // 模拟登陆
            mv.addObject("mockToken", DesformUtils.getMockToken());
            // 最后返回 model and view
            mv.setViewName("desform/formGenerateExternal");
            return mv;
        } catch (JeecgBootException e) {
            mv.addObject("message", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            mv.addObject("message", e.getMessage());
        }
        mv.setViewName("desform/error");
        return mv;
    }

}
